package com.company.test30.CharSoftware;

import javax.swing.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by v on 16-12-5.
 */
public class Server extends JApplet implements Runnable{
    private ChatPanel chatPanel=new ChatPanel();
    //服务端的相关组件
    private ServerSocket server;
    private Socket socket;
    private DataOutputStream output;
    private DataInputStream input;

    public Server(){
        add(chatPanel);
        Thread thread=new Thread(this);
        thread.start();
    }

    @Override
    public void init() {
        super.init();
        setSize(700,500);
    }

    @Override
    public void run() {
        try{
            //客户端与服务器的初始化工作
            server=new ServerSocket(8000);
            System.out.println("正在等待客户端接入……");
            socket=server.accept();
            System.out.println("成功接入");
            input=new DataInputStream(socket.getInputStream());
            output=new DataOutputStream(socket.getOutputStream());
            //启动一个监听器负责发送信息
            chatPanel.jtaInput.addKeyListener(
                    new MyKeyListener(chatPanel,output,"可爱的我"));
            //启动一个线程负责接受信息
            Thread thread=new Thread(new ReceptionMessage(chatPanel,input));
            thread.start();
        }catch (IOException ex){
            ex.printStackTrace();
        }
    }
}
